package com.shenzhen.horselive.ui.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import com.alipay.sdk.app.PayTask;
import com.flqy.baselibrary.utils.GlideHelper;
import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.base.AppBarActivity;
import com.shenzhen.horselive.beans.AppBean;
import com.shenzhen.horselive.beans.FabuFanwei;
import com.shenzhen.horselive.beans.FabuGuanBoBean;
import com.shenzhen.horselive.beans.MessageEventWXPayresult;
import com.shenzhen.horselive.beans.PayResultBean;
import com.shenzhen.horselive.beans.PayWayBean;
import com.shenzhen.horselive.beans.SendRedRulersBean;
import com.shenzhen.horselive.databinding.ActivityAppRedpackageBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;
import com.shenzhen.horselive.utils.PayResult;
import com.shenzhen.horselive.wx.WXManager;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class AppRedpackageActivity extends AppBarActivity {


    ActivityAppRedpackageBinding  binding;


    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what)
            {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        checkPayResult();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。 showAlert(PayDemoActivity.this, getString(R.string.pay_failed) + payResult);
                        showToast("支付取消");

                    }
                    break;
            }

            super.handleMessage(msg);
        }
    };



    //微信支付回调
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEventWXPayresult event) {
        //微信支付的回调
        if (event.getCode()==0)
        {
            checkPayResult();
        }else
        {
            showToast("支付取消");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityAppRedpackageBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setStyleDark();
        setTitle("应用红包");
        setMenuText("我的应用");
        initView();
        initData();
    }


    String  orderrCode;
    String  channelTag;
    //查询支付是否成功
    private void checkPayResult() {
        if (orderrCode==null||channelTag==null)
        {
            return;
        }
        //支付成功
        ApiFactory.getApiService().getPayResult(User.get().getMyInfo().getToken()
                ,orderrCode,channelTag
        ).compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<PayResultBean>(this) {
                    @Override
                    protected void onNextInActive(PayResultBean payResultBean) {
                        if (payResultBean.isSuccess()&&payResultBean.getData().getPayStatus()==1)
                        {
                            showToast("发送红包成功");
                            finish();
                        }
                        else {
                            showToast(payResultBean.getErrMessage());
                        }
                    }
                });
    }







    double  maxAmount;
    double  minAmount;
    int  minNum;
    private void initData() {
        //获取发送的规则
        ApiFactory.getApiService().sendRedLimitRulers(User.get().getMyInfo().getToken())
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<SendRedRulersBean>(this) {
                    @Override
                    protected void onNextInActive(SendRedRulersBean sendRedRulersBean) {
                        if (sendRedRulersBean.isSuccess())
                        {
                            maxAmount = Double.parseDouble(sendRedRulersBean.getData().getMaxAmount());
                            minAmount = Double.parseDouble(sendRedRulersBean.getData().getMinAmount());
                            minNum = sendRedRulersBean.getData().getMinNum();
                            binding.tvTextSendAmountNotice.setText(String.format("（不可低于%s元,不可高于%s元）",minAmount+"",maxAmount+""));
                            binding.tvTextSendNumNotice.setText(String.format("（不可低于%s个）",minNum+""));
                        }
                    }
                });

        //支付渠道
        ApiFactory.getApiService().getPayWays(User.get().getMyInfo().getToken())
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<PayWayBean>(this) {
                    @Override
                    protected void onNextInActive(PayWayBean payWayBean) {
                        if (payWayBean.isSuccess())
                        {
                            binding.payviews.setList(payWayBean.getData());
                        }
                    }
                });

    }




    private void initView() {
        binding.imgAddApp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //选择app
             Intent  intent=   new Intent(AppRedpackageActivity.this,AddAppActivity.class);
             startActivityForResult(intent,1000);
            }
        });
        binding.tvChooseAddr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(AppRedpackageActivity.this,RedPackageLimitActivity.class),1001);
            }
        });

       binding.linerPayGo.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               submit();
           }
       });

       //实时展示金额
        binding.etMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String  money = s.toString();
                if (TextUtils.isEmpty(money))
                {
                    binding.tvFenzhiPay.setText("支付金额：¥ 0.00");

                }else
                {
                    binding.tvFenzhiPay.setText("支付金额：¥ "+money);
                }
            }
        });

        //编辑应用信息
        binding.imgEditApp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (appBean==null)
                    return;
                Intent intent = new Intent(AppRedpackageActivity.this,AddAppActivity.class);
                intent.putExtra("data",appBean);
                startActivityForResult(intent,1000);
            }
        });
        //切换应用信息
        binding.imgRechageApp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent  intent = new Intent(AppRedpackageActivity.this,MyAppActivity.class);
                intent.putExtra("iscall",true);
                startActivityForResult(intent,1000);
            }
        });

    }

    //支付红包
    private void submit() {
        String   content = binding.etText.getText();
        if (TextUtils.isEmpty(content))
        {
            showToast("请填写阐述");
            return;
        }
        String  money = binding.etMoney.getText().toString();
        if (TextUtils.isEmpty(money))
        {
            showToast("请填写金额");
            return;
        }
        if (Double.parseDouble(money)<minAmount||Double.parseDouble(money)>maxAmount)
        {
            showToast("红包金额需在"+minAmount+"元至"+maxAmount+"元之间");
            return;
        }

        String  num = binding.etNum.getText().toString();
        if (TextUtils.isEmpty(num))
        {            showToast("请填写数量");

            return;
        }
        if (Integer.parseInt(num)<minNum)
        {
            showToast("红包个数不能小于"+minNum+"个");
            return;
        }

        //领取范围
        if (appBean==null)
        {
            showToast("请添加应用");
            return;
        }
        if (fabuFanwei==null)
        {
            showToast("请选择发布范围");
            return;
        }
        if (binding.payviews.getPayWayItem()==null)
        {
            showToast("暂时没有可用的支付渠道");
            return;
        }

        ApiFactory.getApiService().appRedPackage(
                User.get().getMyInfo().getToken(),appBean.getId()+"",content,binding.payviews.getPayWayItem().getChannelTag(),money
                ,num,fabuFanwei.getRange()+"",fabuFanwei.getLng()+"",fabuFanwei.getLat()+"",fabuFanwei.getProvence(),fabuFanwei.getProvenceCode()
        )
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<FabuGuanBoBean>(this) {
                    @Override
                    protected void onNextInActive(FabuGuanBoBean fabuGuanBoBean) {
                        if (fabuGuanBoBean.isSuccess())
                        {
                            orderrCode = fabuGuanBoBean.getData().getOrderCode();
                            channelTag = binding.payviews.getPayWayItem().getChannelTag();
                            //掉起支付
                            if (binding.payviews.getPayWayItem().getChannelName().contains("微信"))
                            {
                                WXManager.getInstance().goToPay(fabuGuanBoBean.getData().getPayResult());
                            }else  if (binding.payviews.getPayWayItem().getChannelName().contains("支付宝"))
                            {
                                Runnable payRunnable = new Runnable() {

                                    @Override
                                    public void run() {
                                        PayTask alipay = new PayTask(AppRedpackageActivity.this);
                                        Map<String,String> result = alipay.payV2(fabuGuanBoBean.getData().getPayResult(),true);
                                        Message msg = new Message();
                                        msg.what = SDK_PAY_FLAG;
                                        msg.obj = result;
                                        handler.sendMessage(msg);
                                    }
                                };
                                // 必须异步调用
                                Thread payThread = new Thread(payRunnable);
                                payThread.start();

                            }
                        }else
                        {
                            showToast(fabuGuanBoBean.getErrMessage());
                        }
                    }
                });

    }
    @Override
    protected void onActionMenuViewClick() {
        super.onActionMenuViewClick();
        startActivity(new Intent(this,MyAppActivity.class));
    }


    AppBean  appBean;
    FabuFanwei  fabuFanwei;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1000&&resultCode==1001)
        {
            if (data!=null&&data.getSerializableExtra("data")!=null)
            {
                //添加app过来的
            appBean = (AppBean) data.getSerializableExtra("data");
            binding.containerAddContent.setVisibility(View.VISIBLE);
            binding.imgAddApp.setVisibility(View.GONE);
           binding.linerEditApp.setVisibility(View.VISIBLE);
            GlideHelper.loadImage(appBean.getApplicationLogo(),binding.imgAddImg);
            binding.tvAppName.setText(appBean.getApplicationName());
            binding.tvAppContent.setText(appBean.getApplicationDesc());
            }
            else
            {
                //删除或者修改过来的
                appBean = null;
                binding.containerAddContent.setVisibility(View.GONE);
                binding.imgAddApp.setVisibility(View.VISIBLE);
                binding.linerEditApp.setVisibility(View.GONE);
            }

        }
        else if (requestCode==1001&&resultCode==1001)
        {
            //选择地址
            fabuFanwei = (FabuFanwei) data.getSerializableExtra("data");
            binding.tvChooseAddr.setText(fabuFanwei.getName());
        }
    }
}